In Java, the finally block is used to execute important code such as closing a connection, etc. The finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be executed regardless of whether an exception occurs or not.
Here’s the syntax of a try-catch-finally block in Java:
try-catch-finally block syntax
try {
// code that might generate an exception
} catch (Exception e) {
// code to handle the exception
} finally {
// code to be executed regardless of an exception
}
Example of finally Block Here’s an example of how to use the finally block in Java:
Example of using finally in try-catch in exception handling using java
public class Main {
public static void main(String []args) {
try {
int data = 25/5;
System.out.println(data);
} catch(NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output
5
finally block is always executed
rest of the code...
In this example, the try block does not throw any exception, so the catch block is skipped. However, the finally block is executed regardless of whether an exception occurred or not.
Remember, proper exception handling can improve a Java application’s robustness and performance capabilities. It’s an essential part of writing a reliable and fault-tolerant Java program.